import { RequestLog,RequestDeleteLog,RequestManager,RequestAddLog } from "@/api";
import { ElMessage } from "element-plus";
import type { ILog } from "@/utils/types";
import type { LogAccount } from '@/utils/types'
import { shallowRef, ref, onMounted, onBeforeUnmount,type Ref, } from "vue";

// import {addEdit} from './addEdit'
// const {valueHtml} = addEdit()
/**
 * 日志列表
 * @returns 
 */
export const getLog = () => {
    let userInfo = localStorage.getItem('user-key')//用户信息
    let logList: Ref<Array<ILog>> = ref([])//日志列表
    let disableAddRoleForm: Ref<boolean> = ref(false) //添加角色对话框显示
    let total = ref(0)
    const currentNo = ref(1)
    const pageSize = 10
    const { username } = userInfo
    console.log('username121>>',username);
    
    const user = {
        username,
        currentNo:currentNo.value,
        pageSize
    }
    const search = ref('')


    // 修改
const handleEdit = (index: number, row: ILog) => {
    console.log(index, row)
    disableAddRoleForm.value = true
    }
    // 删除
const handleDelete = async(index: number, row: ILog) => {
    console.log(index, 'row>>123',row.m_id)
    let data = await RequestDeleteLog(row.m_id)
    console.log('123>>',data);
    
    }
    

// 请求日志列表
    const getLogList = async() => {
        let data = await RequestLog(user)
    console.log('loglist--data>>', data);
    const { resultCode, resultInfo } = data
    if (resultCode === 1) {
        logList.value = resultInfo.list
        total.value = resultInfo.total
        console.log('total.value>>',total.value);
        
        // console.log('logList.value',logList.value);
        
    } else {
        ElMessage.error('请求日志数据失败！')
    }
    }    

    
    /**
     * 分页
     * @param e 
     */
    const changePage = (e:any) => {
        console.log('e>>',e.target.innerHTML);
        currentNo.value = e.target.innerHTML
        console.log('currentNo.value>>',currentNo.value);
        // getLogList()
    }

    
    
    return {
        logList,
        total,
        search,
        currentNo,
        changePage,
        getLogList,
        handleEdit,
        handleDelete,
        disableAddRoleForm
    }
    
}


/**
 * 添加日志
 */
export const AddLog = () => {
        // 日志内容 HTML
     let valueHtml = ref('')
    

let logAccount: Ref<LogAccount> = ref({
    username: '',
    nick: '',
    m_id: 0,
    logtime: '',
    content: '',
    category: 0,
})
const rules = ref({
    m_id: [{ required: true, message: '日志ID非空!', trigger: 'blur' }],
    category: [{ required: true, message: '日志类型非空!', trigger: 'blur' }],
    content: [{ required: true, message: '日志内容非空!', trigger: 'blur' }],
    logtime: [{ required: true, message: '日志时间非空!', trigger: 'blur' }],
})

// 从本地获取用户信息
let users = localStorage.getItem('user-key')
const user = JSON.parse(users)
    console.log('users>>', user);
    

    // 格式化日期对象
    Date.prototype.Format = function (fmt:any) {
        var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
        }

// 检查操作员，获取m_id
    RequestManager(user.username).then(data => {
        const { resultCode, resultInfo } = data
        if (resultCode === 1) {
            // console.log('resultInfo>>', resultInfo);
            logAccount.value.username = user.username
            logAccount.value.nick = user.nick
            let m_id = resultInfo[0].m_id
            logAccount.value.logtime = (new Date()).Format(`yyyy-MM-dd THH:mm:ss.SZ`)
            logAccount.value.m_id = m_id
            logAccount.value.content = valueHtml.value
        } else {
            ElMessage.error('数据请求失败！')
        }
    }).catch(error => {
        console.log(error);
     })

/**
    操作日志
 * 
 */
/**
 * 日志内容
 * @returns 
 */
 const addEdit = () => {
 
    // console.log('1234567899>>', logAccount);
    // console.log('1234567899>>', logAccount);

       // 编辑器实例，必须用 shallowRef
   const editorRef = shallowRef()

    // 模拟 ajax 异步获取内容
     onMounted(() => {        
        // setTimeout(() => {
        //     valueHtml.value = logAccount.value.content
        // }, 1000)
    })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor: any) => {
        editorRef.value = editor // 记录 editor 实例，重要！
        
    }


    return {
        editorRef,
        valueHtml,
        mode: 'default', // 或 'simple'
        toolbarConfig,
        editorConfig,
        handleCreated,
    };
}


    /**
     * 添加日志
     */
    const onLogAddSubmit = () => {
        // console.log('logAccount。。》',logAccount.value);
        
        //     const { username, nick, m_id,logtime,content,category } = logAccount.value
        //     console.log('dayin>>',username);
            
        //     const formData = new FormData()
        //     formData.append('username', username)
        //     formData.append('nick', nick)
        //     formData.append('mid', m_id)
        //     formData.append('logtime', logtime)
        //     formData.append('category', category)
        // formData.append('content', content)
        // console.log('formData>>',formData);
        console.log('editorRef.value>>',valueHtml.value);
        
            RequestAddLog(logAccount.value).then(data => {
                const { resultCode, resultInfo } = data
                if (resultCode === 1) {
                    ElMessage.success('添加日志成功!')
                } else {
                    ElMessage.error('添加账户失败！')
                }
            })
    }
    return {
        logAccount,
        rules,
        onLogAddSubmit,
        addEdit
    }
}
